用法:sorted(串列)
sorted 會將串列由小到大排列 :
串列裡面的資料必須都是相同資料型態才能進行排序
排序後會產生一個新的字串,不會更改原始的字串
sort v.s sorted
例1. sort v.s. sorted
shoppingCart = ['juice', 'book', 'apple']
shoppingCart.sort()
print(shoppingCart)
# ['apple', 'book', 'juice']
shoppingCart = ['juice', 'book', 'apple']
sorted_shoppingCart = sorted(shoppingCart)
print(sorted_shoppingCart)
# ['apple', 'book', 'juice']
print(shoppingCart)
# ['juice', 'book', 'apple']
例2.
score = [55, 1, 15, 60, 99, 47, 32]
sorted_score = sorted(score)
print(sorted_score)
# [1, 15, 32, 47, 55, 60, 99]
database = ['six', '15', '9']
sorted_database = sorted(database)
print(sorted_database)
# ['15', '9', 'six']
# 因為數字小於英文字母,字串中 1 小於 9,所以 15 優先於 9
用法:sorted ( 串列, reverse = True / False )
例1.
shoppingCart = ['apple', 'juice', 'book']
sorted_shoppingCart = sorted(shoppingCart)
reverse_sorted_shoppingCart = sorted(shoppingCart, reverse=True)
print(sorted_shoppingCart, reverse_sorted_shoppingCart, sep='\n')
# ['apple', 'book', 'juice']
# ['juice', 'book', 'apple']
用法:
sorted ( 串列, key = 排序規則 )
例1.
shoppingCart = ['apple', 'juice', 'book', 'egg', 'elephant', 'addidas']
sorted_shoppingCart = sorted(shoppingCart, key=len)
reverse_sorted_shoppingCart = sorted(shoppingCart, reverse=True, key=len)
print(sorted_shoppingCart, reverse_sorted_shoppingCart, sep='\n')
# ['egg', 'book', 'apple', 'juice', 'addidas', 'elephant']
# ['elephant', 'addidas', 'apple', 'juice', 'book', 'egg']
例2.
def second(i):
return i[1]
data = ['fish', 'head', 'cake']
data = sorted(data, key=second)
print(data)
# ['cake', 'head', 'fish']
重點整理: